package edu.core.testapp.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.core.testapp.server.PMF;
import edu.core.testapp.server.StoredFile;

public class FileServlet extends HttpServlet {
	
	public static final String MIME_APPLICATION_OCTECT_STREAM = "application/octet-stream";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		final String id = req.getParameter("id");
		
		String mimetype = MIME_APPLICATION_OCTECT_STREAM;
		resp.setContentType(mimetype);
		
		//ServletOutputStream sos = resp.getOutputStream();
		//sos.write(("Hello World").getBytes());
		
		String fileName = "";
		String fileContent = "";
		if (id != null) {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			StoredFile f = pm.getObjectById(StoredFile.class, id);
			fileName = f.getName();
			fileContent = new String(f.getData());
		}
		
		PrintWriter pw = resp.getWriter();
		pw.println("Hello World");
		pw.println((id == null ? "NULL" : id));
		pw.println(fileName);
		pw.println(fileContent);
		pw.close();
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

}
